import React, { useState, useEffect } from 'react'
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  SearchOutlined,
  CopyOutlined,
  PlayCircleOutlined,
  TableOutlined
} from '@ant-design/icons'
import { PageResult, DataComponent } from '@/types/index'
import { request } from '@/services/api'
import type { ColumnsType } from 'antd/es/table'

const { Option } = Select
const { TextArea } = Input

interface DataComponentQueryForm {
  name?: string
  type?: string
  status?: string
}

const DataComponentProcessing: React.FC = () => {
  const [loading, setLoading] = useState(false)
  const [componentList, setComponentList] = useState<DataComponent[]>([])
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const [queryForm] = Form.useForm<DataComponentQueryForm>()
  const [createForm] = Form.useForm()
  const [createModalVisible, setCreateModalVisible] = useState(false)
  const [editingComponent, setEditingComponent] = useState<DataComponent | null>(null)
  const [statistics, setStatistics] = useState({
    total: 0,
    table: 0,
    list: 0,
    active: 0
  })

  // 查询数据组件列表
  const fetchComponentList = async (params?: any) => {
    setLoading(true)
    try {
      const queryParams = {
        current: pagination.current,
        size: pagination.pageSize,
        ...queryForm.getFieldsValue(),
        ...params
      }

      const response = await request.get<PageResult<DataComponent>>('/data-components', queryParams)
      setComponentList(response.data.records)
      setPagination({
        ...pagination,
        total: response.data.total,
        current: response.data.current
      })
    } catch (error) {
      message.error('查询失败')
    } finally {
      setLoading(false)
    }
  }

  // 获取统计信息
  const fetchStatistics = async () => {
    try {
      const response = await request.get('/data-components/statistics')
      setStatistics(response.data)
    } catch (error) {
      console.error('获取统计信息失败:', error)
    }
  }

  // 创建/更新数据组件
  const handleCreateOrUpdate = async (values: any) => {
    try {
      const requestData = {
        component: {
          ...values,
          id: editingComponent?.id,
          creator: 'current_user'
        },
        fields: []
      }

      if (editingComponent) {
        await request.put(`/data-components/${editingComponent.id}`, requestData)
        message.success('更新成功')
      } else {
        await request.post('/data-components', requestData)
        message.success('创建成功')
      }
      setCreateModalVisible(false)
      setEditingComponent(null)
      createForm.resetFields()
      fetchComponentList()
      fetchStatistics()
    } catch (error) {
      message.error(editingComponent ? '更新失败' : '创建失败')
    }
  }

  // 删除数据组件
  const handleDelete = async (id: number) => {
    try {
      await request.delete(`/data-components/${id}`)
      message.success('删除成功')
      fetchComponentList()
      fetchStatistics()
    } catch (error) {
      message.error('删除失败')
    }
  }

  // 编辑数据组件
  const handleEdit = (record: DataComponent) => {
    setEditingComponent(record)
    createForm.setFieldsValue({
      name: record.name,
      displayName: record.displayName,
      description: record.description,
      type: record.type,
      dataSourceType: record.dataSourceType,
      refreshInterval: record.refreshInterval
    })
    setCreateModalVisible(true)
  }

  // 表格列定义
  const columns: ColumnsType<DataComponent> = [
    {
      title: '组件名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      ellipsis: true
    },
    {
      title: '显示名称',
      dataIndex: 'displayName',
      key: 'displayName',
      width: 150,
      ellipsis: true
    },
    {
      title: '组件类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => {
        const typeConfig = {
          TABLE: { color: 'blue', text: '表格' },
          LIST: { color: 'green', text: '列表' },
          CARD: { color: 'orange', text: '卡片' },
          TREE: { color: 'purple', text: '树形' },
          FORM: { color: 'cyan', text: '表单' },
          DETAIL: { color: 'magenta', text: '详情' },
          SEARCH: { color: 'gold', text: '搜索' },
          FILTER: { color: 'lime', text: '过滤' }
        }
        const config = typeConfig[type as keyof typeof typeConfig]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '数据源类型',
      dataIndex: 'dataSourceType',
      key: 'dataSourceType',
      width: 120,
      render: (type: string) => {
        const typeConfig = {
          WIDE_TABLE: { color: 'blue', text: '宽表' },
          DATABASE: { color: 'green', text: '数据库' },
          ELASTICSEARCH: { color: 'orange', text: 'ES' },
          API: { color: 'purple', text: 'API' },
          FILE: { color: 'cyan', text: '文件' }
        }
        const config = typeConfig[type as keyof typeof typeConfig]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string) => {
        const statusConfig = {
          DRAFT: { color: 'default', text: '草稿' },
          ACTIVE: { color: 'success', text: '启用' },
          INACTIVE: { color: 'warning', text: '停用' },
          DELETED: { color: 'error', text: '已删除' }
        }
        const config = statusConfig[status as keyof typeof statusConfig]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      ellipsis: true
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record: DataComponent) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="预览">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => {
                message.info('预览功能开发中')
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确认删除？"
            description="删除后不可恢复，请谨慎操作"
            onConfirm={() => handleDelete(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ]

  useEffect(() => {
    fetchComponentList()
    fetchStatistics()
  }, [])

  return (
    <div>
      {/* 页面头部 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1>数据组件加工</h1>
        <Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditingComponent(null)
              createForm.resetFields()
              setCreateModalVisible(true)
            }}
          >
            创建数据组件
          </Button>
        </Space>
      </div>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic title="总数" value={statistics.total} prefix={<TableOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="表格组件" value={statistics.table} valueStyle={{ color: '#1890ff' }} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="列表组件" value={statistics.list} valueStyle={{ color: '#52c41a' }} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="已启用" value={statistics.active} valueStyle={{ color: '#f5222d' }} />
          </Card>
        </Col>
      </Row>

      {/* 查询表单 */}
      <Card style={{ marginBottom: 24 }}>
        <Form
          form={queryForm}
          layout="inline"
          onFinish={(values) => fetchComponentList({ current: 1, ...values })}
        >
          <Form.Item name="name" label="组件名称">
            <Input placeholder="请输入组件名称" allowClear />
          </Form.Item>
          <Form.Item name="type" label="组件类型">
            <Select placeholder="请选择类型" allowClear style={{ width: 120 }}>
              <Option value="TABLE">表格</Option>
              <Option value="LIST">列表</Option>
              <Option value="CARD">卡片</Option>
              <Option value="TREE">树形</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" allowClear style={{ width: 120 }}>
              <Option value="DRAFT">草稿</Option>
              <Option value="ACTIVE">启用</Option>
              <Option value="INACTIVE">停用</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                查询
              </Button>
              <Button
                onClick={() => {
                  queryForm.resetFields()
                  fetchComponentList({ current: 1 })
                }}
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      {/* 数据表格 */}
      <Card>
        <Table<DataComponent>
          columns={columns}
          dataSource={componentList}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setPagination({ ...pagination, current: page, pageSize: size })
              fetchComponentList({ current: page, size })
            }
          }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 创建/编辑模态框 */}
      <Modal
        title={editingComponent ? '编辑数据组件' : '创建数据组件'}
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false)
          setEditingComponent(null)
          createForm.resetFields()
        }}
        onOk={() => createForm.submit()}
        width={600}
        destroyOnClose
      >
        <Form
          form={createForm}
          layout="vertical"
          onFinish={handleCreateOrUpdate}
        >
          <Form.Item
            name="name"
            label="组件名称"
            rules={[{ required: true, message: '请输入组件名称' }]}
          >
            <Input placeholder="请输入组件名称" />
          </Form.Item>
          <Form.Item
            name="displayName"
            label="显示名称"
            rules={[{ required: true, message: '请输入显示名称' }]}
          >
            <Input placeholder="请输入显示名称" />
          </Form.Item>
          <Form.Item name="description" label="描述">
            <TextArea rows={3} placeholder="请输入描述" />
          </Form.Item>
          <Form.Item
            name="type"
            label="组件类型"
            rules={[{ required: true, message: '请选择组件类型' }]}
          >
            <Select placeholder="请选择组件类型">
              <Option value="TABLE">表格组件</Option>
              <Option value="LIST">列表组件</Option>
              <Option value="CARD">卡片组件</Option>
              <Option value="TREE">树形组件</Option>
              <Option value="FORM">表单组件</Option>
              <Option value="DETAIL">详情组件</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="dataSourceType"
            label="数据源类型"
            rules={[{ required: true, message: '请选择数据源类型' }]}
          >
            <Select placeholder="请选择数据源类型">
              <Option value="WIDE_TABLE">数据宽表</Option>
              <Option value="DATABASE">数据库</Option>
              <Option value="ELASTICSEARCH">Elasticsearch</Option>
              <Option value="API">REST API</Option>
              <Option value="FILE">文件数据源</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default DataComponentProcessing